package com.demo.service;


import com.demo.esper.event.AbstractEsperEvent;
import com.demo.esper.statement.EsperRuleConfig;
import com.demo.model.redis.EsperRecord;
import com.demo.repository.redis.EsperRecordRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class EsperService {

    @Resource
    private EsperRecordRepository esperRecordRepository;

    public List<EsperRuleConfig> getEsperRuleConfigList(String ruleGroupName) {
        EsperRuleConfig config = new EsperRuleConfig();
        config.setRuleId(1L);
        config.setRuleGroupName(ruleGroupName);
        config.setStatement("@Drop @Priority(20) select eventId as eventId, 20 * 10000 as targetAmount from data where age >= 0  and age <= 10");
        EsperRuleConfig config2 = new EsperRuleConfig();
        config2.setRuleId(2L);
        config2.setRuleGroupName(ruleGroupName);
        config2.setStatement("@Drop @Priority(100) select eventId as eventId, 20 * 10000 as targetAmount from data where age >= 3  and age <= 11");
        List<EsperRuleConfig> configList = new ArrayList<>();
        configList.add(config);
        configList.add(config2);
        return configList;
    }

    public void saveEsperRecord(Long eventId, String ruleGroupName, AbstractEsperEvent event) {
        EsperRecord record = new EsperRecord();
        record.setEventId(eventId);
        record.setCreateTime(new Date());
        record.setRuleGroupName(ruleGroupName);
        record.setEvent(event);
        esperRecordRepository.save(record);
    }

    public void updateEsperRecord(Long eventId, Map<String, Object> result) {
        EsperRecord record = esperRecordRepository.findOne(eventId);
        record.setResult(result);
        esperRecordRepository.save(record);
    }

    public Map<String, Object> getEsperResult(Long eventId) {
        EsperRecord record = esperRecordRepository.findOne(eventId);
        if (record == null) {
            return null;
        }
        return record.getResult();
    }


}
